package com.inspur.cloud.util;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * 加密解密工具类 AESUtil.
 * 此工具的加密与DESUtil中的aes加密有所区别
 */
public class AESUtil {

    /**
     * The aes 加密对象.
     */
    private static Cipher aesEnCipher = null;

    /**
     * The aes 解密对象.
     */
    private static Cipher aesDeCipher = null;

    private static final String key = "incloudOS@inspur";

    /* AES加密模式 */
    private static final String AES_ENCRYTION_MODE = "AES";

    public static final Integer FORMAT_HEX = 0;

    public static final Integer FORMAT_BASE64 = 1;

    static {
        try {
            SecretKeySpec aeskey = new SecretKeySpec(key.getBytes("UTF-8"), AES_ENCRYTION_MODE);
            aesEnCipher = Cipher.getInstance(AES_ENCRYTION_MODE);// 创建密码器
            aesEnCipher.init(Cipher.ENCRYPT_MODE, aeskey);// 初始化
            aesDeCipher = Cipher.getInstance(AES_ENCRYTION_MODE);// 创建密码器
            aesDeCipher.init(Cipher.DECRYPT_MODE, aeskey);// 初始化
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 默认构造器.
     */
    private AESUtil() {
    }

    /**
     * @param data
     * @param format 0表示16进制，1表示base64
     * @return
     */
    public static String encrypt(String data, Integer format) {
        try {
            byte[] byteContent = data.getBytes("utf-8");
            byte[] result = aesEnCipher.doFinal(byteContent); // 加密
            if (format == FORMAT_HEX) {
                return parseByte2HexStr(result);
            } else if (format == FORMAT_BASE64) {
                return Base64.encodeBase64String(result);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * AES解密.
     *
     * @param deCodeData 待解密内容
     * @return the string
     */
    public static String decrypt(String deCodeData, Integer format) {
        try {
            byte[] dec = null;
            if (format == FORMAT_HEX) {
                dec = parseHexStr2Byte(deCodeData);

            } else if (format == FORMAT_BASE64) {
                dec = Base64.decodeBase64(deCodeData);
            }
            byte[] result = aesDeCipher.doFinal(dec);
            return new String(result); // 加密
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    private static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr == null || hexStr.length() == 0) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
}
